<?php

namespace common\models\user;

use Yii;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%user_im}}".
 *
 * @property int $id
 * @property int $user_id 用户ID
 * @property string $im_token IM Token
 * @property int $expired_at 过期时间
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 */
class UserIm extends \common\db\ActiveRecord {

    const STATUS_DELETED = -1;
    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%user_im}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id', 'expired_at', 'created_at', 'updated_at'], 'integer'],
            [['im_token'], 'required'],
            [['im_token'], 'string', 'max' => 255],
            [['user_id'], 'unique'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'im_token' => 'IM Token',
            'expired_at' => '过期时间',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    protected function validateTokenAvailable() {
        if ($this->im_token) {
            if (!$this->expired_at || $this->expired_at < time()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 融云TOKEN
     */
    public function getToken($default = null) {
        if ($this->validateTokenAvailable()) {
            return $this->im_token;
        }
        return static::findOrRegister($this->user_id, $default);
    }

    /**
     * 获取并注册token
     */
    public static function findOrRegister($uid, $default = null) {
        $user = UserMeta::findOne($uid);
        if (!$user) {
            return $default;
        }
        $im = static::findOrNew([
            'user_id' => $user->id
        ]);
        $transport = Yii::$app->rongyun->transport('user');
//        $rongCloundToken = call_user_func_array(array($transport, "getToken"), [$user->id, $user->username, $user->portrait]);
        $rongCloundToken = $transport->getToken($user->id, $user->username, $user->portrait);
        $token = ArrayHelper::getValue($rongCloundToken, 'token', $default);
        if ($token) {
            $im->im_token = $token;
            if (!$im->save()) {
                Yii::error($im->errors);
            }
        }
        return $token;
    }

}
